<template>
  <div>
    <!-- <AutoComplete
      v-model="searchValue"
      @on-search="onSearch"
      @on-change="onChange"
      @on-select="onSelectSearch"
      @on-clear="onClear"
      :placeholder="'请输入节点名称或编码'"
      style="padding: 0 10px; margin: auto; display: block;"
      icon="md-search"
      clearable
    >
      <Option v-for="(option, index) in searchResult" :value="option" :key="index">{{option}}</Option>
      <p
        class="complete-more get-complete-more"
        v-if="searchResult.length >= 10 && isShowMore"
        @click="showMore"
      >查看更多</p>
    </AutoComplete> -->
    <!-- <Spin v-if="isShowSpin">{{ searchHint }}</Spin> -->
    <el-tree
      ref="tree"
      :data="rootNode"
      :props="treeProps"
      node-key="nodeCode"
      :default-expanded-keys="expandedKeys"
      :load="loadData"
      lazy
      :render-content="renderContent"
      :expand-on-click-node="false"
      class="tree-box"
      icon-class="ivu-icon-ios-arrow-forward"
      highlight-current
    ></el-tree>
  </div>
</template>

<script>
import treeAPI from '@/api/treeApi.js'
export default {
  name: 'orgTree',
  data() {
    return {
      searchValue: "",
      searchResult: [],
      searchResultNode: [],
      isShowMore: true,
      pressCount: 0,
      expandedKeys: [],
      searchHint: '',
      rootNode: [],
      treeProps: {
        label: "nodeCode",
        children: "childrenDept",
        isLeaf: "isLeaf"
      },
      isShowSpin: false,
      pageNum: 1,
      
    }
  },
  props: {
    treeObj: {
      type: Object,
      default() {
        return {};
      }
    },
    comp: { 
      type: String,
      default: 'orgManage'
    },
    buCode: {
      type: String,
      default: ''
    },
    dcPeriod: {
      type: String,
      default: ''
    },
    isClose: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    onSearch(value) {
      this.searchResultNode = [];
      this.pageNum = 1;
      this.isShowMore = true;
      this.searchResult = [];
      if (value && value.indexOf("/") == -1) { 
        this.pressCount++;
        let param = {
          condition: {
            nodeCode: this.comp === 'orgManage' ? 'ZZ-' + this.$store.state.userBu.key : 'GJ-' + this.$store.state.userBu.key,
            nodeName: value
          },
          pageNum: 1,
          pageSize: 10
        };
        // 延时查询
        setTimeout(() => {
          if (this.pressCount == 1) {
            this.pressCount = 0;
            this.isShowSpin = true;
            this.searchHint = '搜索组织';
            treeAPI.selectTreeNode(param).then(data => {
              // 查询完时，查询条件已清空，不再显示查询结果
              if (this.searchValue == "") {
                this.isShowSpin = false;
                this.searchHint = "";
                return;
              }
              this.searchResultNode = data.records;
              if (data.records.length > 0) {
                this.isShowSpin = false;
                this.searchHint = "";
                data.records.forEach(node => {
                  this.searchResult.push(node.nodeNamePath); // 由nodeNamePath组成的一维数组
                  // let data = {};
                  // data.nodeNamePath = node.nodeNamePath;
                  // data.nodePath = node.nodePath;
                  // this.treeList.push(data);
                });
              } else {
                this.isShowSpin = true;
                this.searchHint = '无查询结果';
              }
            });
          } else {
            this.pressCount--;
          }
        }, 800);
      }
    },
    showMore() {
      this.getSelectNode(this.searchValue);
    },
    getSelectNode(value) {
      // 点击查看更多，pageNum改为2，从第二页开始查询
      this.pageNum++;
      if (value && value.indexOf("/") == -1) {
        let param = {
          condition: {
            nodeCode: this.comp === 'orgManage' ? 'ZZ-' : 'GJ-' + this.$store.state.userBu.key,
            nodeName: value
          },
          pageNum: this.pageNum,
          pageSize: 10
        };
        treeAPI.selectTreeNode(param).then(data => {
          if (data.records.length > 0) {
            let nodeNamePathArr = [];
            // let nodeArr = [];
            this.searchResultNode = this.searchResultNode.concat(data.records);
            data.records.forEach(node => {
              nodeNamePathArr.push(node.nodeNamePath); // 查询出来的nodeNamePath形成的一维数组

              // let data = {};
              // data.nodeNamePath = node.nodeNamePath;
              // data.nodePath = node.nodePath;
              // nodeArr.push(data); // 查询出来的nodeNamePath和nodePath形成的二维数组
            });
            this.$nextTick(() => {
              this.searchResult = this.searchResult.concat(nodeNamePathArr); // AutoComplete组件显示的数据
              // this.treeList = this.treeList.concat(nodeArr);
            });
          } else {
            // 查询结果，data.records为空数组时，隐藏查看更多按钮
            this.isShowMore = false;
          }
        });
      }
    },
    onChange(value) {
      if (!value) {
        this.onClear();
      }
    },
    onSelectSearch(value) {
      this.expandedKeys = [];
      this.$refs.tree.store.lazy = false;
      let selectedNode = this.searchResultNode.find(node => {
        return node.nodeNamePath == value;
      });
      this.onNodeSelected(selectedNode);
      this.getParentTreeByTreeNodePath({ nodePath: selectedNode.nodePath }, selectedNode);
    },
    getParentTreeByTreeNodePath(nodePath, selectedNode) {
      treeAPI.getParentTreeByTreeNodePath(nodePath).then(data => {
        this.rootNode = data;
        this.$nextTick(() => {
          this.expandedKeys = [selectedNode.nodeCode];
          this.$refs["tree"].setCurrentKey(this.expandedKeys[0]);
        });
      });
    },
    onClear() { 
      // 隐藏提示信息
      this.searchValue = "";
      this.$refs.tree.store.lazy = true;
      this.rootNode = [];
      this.isShowSpin = false;
      this.searchHint = "";
      // 清空查询结果
      this.searchResult = [];
      this.searchResultNode = [];
      this.init();
    },
    loadData(node, resolve) {
      if (node.level == 0) {
        // 隐藏根节点
        return;
      }
      // 是叶子节点不进行查询
      if (node.isLeaf) {
        resolve([]);
      }
      treeAPI.queryTreeNode(node.data.id).then(children => {
        let data = [];
        for (const child of children) {
          if (child.endNode == "Y") {
            data.push({ ...child, title: child.nodeName, children: [], isLeaf: true });
          } else {
            data.push({ ...child, title: child.nodeName, children: [] });
          }
        }
        resolve(data);
      });
    },
    renderContent(h, { node, data, store }) {
      let isRootNode = node.level == 1
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%"
          },
          class: ["tree-row", data.selected ? "tree-row-selected" : ""]
        },
        [
          h("span", [
            h("Icon", {
              props: {
                type: "ios-paper-outline"
              },
              style: {
                marginRight: "8px",
                fontSize: "14px"
              }
            }),
            h(
              "span",
              {
                class: "ivu-tree-title",
                style: {
                  fontSize: "14px"
                },
                on: {
                  click: () => {
                    this.onNodeSelected(data);
                  }
                },
                attrs: {
                  title: data.title
                }
              },
              data.nodeName
            )
          ]),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                // position: "absolute",
                // right: "2px"
                width: "40px"
              }
            },
            [
             node.level <5 ? h(
                "Button",
                {
                  props: Object.assign({}, this.buttonProps),
                  style: {
                    padding: "1px 3px",
                    borderRadius: "3px"
                  },
                  on: {
                    click: () => {
                      this.append(node, data);
                    }
                  }
                },
                [
                  h("i", {
                    class: "el-icon-plus",
                    style: {
                      lineHeight: 1.5
                    }
                  })
                ]
              ) : '',
              h(
                "Button",
                {
                  props: Object.assign({}, this.buttonProps),
                  class: isRootNode ? "rootNode" : "",
                  style: {
                    padding: "1px 3px 2px",
                    borderRadius: "3px"
                  },
                  on: {
                    click: () => {
                      this.remove(node, data, store);
                    }
                  }
                },
                [
                  h("i", {
                    class: "el-icon-delete",
                    style: {
                      lineHeight: 1.5
                    }
                  })
                ]
              )
            ]
          )
        ]
      );
    },
    // 初始时选中第一个节点
    selectFirstNode() {
      const modelForm = this.rootNode[0];
      console.log("modelForm", modelForm)
      const config = {
          canNotBeEdit: true,
          editAreaTitle: '组织信息',
          modelForm,
          isRoot: true // 是否为根节点
      }
      this.$emit('infoConfig', config)
      this.$refs.tree.setCurrentNode(modelForm);
    },
    init() {
      let param = {
        "condition": {
          "tenantCode": "",
          "treeName": this.$store.state.userBu.value,
          "treeCode": this.$store.state.userBu.key,
        }
      }
      treeAPI.getTree(param).then(res => {
        res.data.records.forEach(item => {
            item.nodeName = item.treeName
            item.nodeCode = item.treeCode
          })
        this.comp === 'orgManage' ? this.rootNode = [res.data.records[0]] : this.rootNode = [res.data.records[1]]
          this.$nextTick(function() {
            this.selectFirstNode();
          });
        })
    },
    // 选中当前树节点
    onNodeSelected(data) {
      if (this.rootNode.some(obj => obj.nodeCode === data.nodeCode)) {
        const config = {
          canNotBeEdit: true,
          editAreaTitle: '组织信息',
          modelForm: data,
          isRoot: true, // 是否为根节点
          isLeaf: data.isLeaf, // 是否为叶子节点
        }
        this.$emit('infoConfig', config)
      } else {
        treeAPI.getTreeNodeDetail({ id: data.id }).then(data => {
          const config = {
            canNotBeEdit: false,
            editAreaTitle: '编辑组织信息',
            modelForm: data,
            isRoot: false, // 是否为根节点
            isLeaf: data.endNode === 'Y' ? true : false // 是否为叶子节点
          }
        this.$emit('infoConfig', config)
        });
      }
    },
    delOrgNode(params) {
      return treeAPI.deleteTreeNode(params).then(res => {
        return res
      })
    },
    delKeyNode(params) {
      return treeAPI.delKeyNode(params).then(res => {
        return res
      })
    },
    // 删除
    remove(node, data) {
      const params = {
        node: {
          id: data.id,
          tenantCode: data.tenantCode,
          nodeType: data.nodeType,
          nodeCode: data.nodeCode,
          nodeName: data.nodeName,
          nodeLevel: 0
        },
        buCode: this.$store.state.userBu.key,
        dcPeriod: this.dcPeriod || this.$store.state.writeablePeriod,
        treeCode: this.comp === 'orgManage' ? 'ZZ-' + this.$store.state.userBu.key : 'GJ-' + this.$store.state.userBu.key,
        isLast: data.endNode === 'N' ? false : true
      }
      this.$confirm({
        content: '确认删除?'
      }).then(async () => {
          const res = this.comp === 'orgManage' ? await this.delOrgNode(params) : await this.delKeyNode(params)
          if (res) {
            this.$message.success({
              content: '删除成功',
              duration: 3
            })
            this.onClear()
          }
        })
        .catch(_ => _)
    },

    append(node, data) {
      treeAPI.queryTreeNode(node.data.id).then(children => {
        const addInfo = {
          isAdd: true,
          id: data.id,
          parentNodePath: data.nodePath || '/' + data.treeCode,
          parentNodeName: data.nodeName,
          parentNodeCode: data.nodeCode,
          tenantCode: data.tenantCode,
          isFirst: children.length === 0
        }
        this.$emit('addInfo', addInfo)
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="less">
.get-complete-more {
  padding: 7px 16px;
  // color: #ff6f4b;
  cursor: pointer;
}
.tree-box {
  display: inline-block;
  width: 100%;
  .ivu-btn:focus {
    box-shadow: none;
  }
  button {
    border: 0px;
    background-color: transparent;
    font-size: 14px;
    // color: #ff6f4b;
    font-weight: bold;
  }
  .el-tree-node {
    button:hover {
      background-color: var(--primary-color-8);
      // color: #ff6f4b;
    }

    .tree-row {
      padding: 3px 0;
      button {
        visibility: hidden;
      }
      &:hover {
        button {
          visibility: visible;
        }
      }
    }
  }

  .ivu-tree-title {
    vertical-align: middle !important;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    width: calc(~"100% - 100px");
  }
  .ivu-tree-title:hover {
    background-color: #0000;
    // color: #ff6f4b;
  }
  .rootNode {
    visibility: hidden !important;
  }
}
.tree-node-button {
  button {
    font-size: 14px;
    height: 34px;
    padding: 3px 23px;
    border-radius: 0px;
    margin-right: 18px;
  }

  // 第一个按钮样式
  // button:first-child {
  //   color: #fff;
  //   background-color: #ff6f4b;
  //   border-color: #ff6f4b;
  // }
}
.visibility {
  visibility: hidden;
}
.page-box-row-left {
  .myForm {
    .ivu-form-item {
      .ivu-form-item-content {
        margin-left: 0px !important;
      }
    }
  }
  .ivu-select-dropdown {
    max-height: 330px !important;
    min-width: auto !important;
    width: 96% !important;
    .ivu-select-dropdown-list {
      width: fit-content;
      .ivu-select-item:hover {
        background: #fff !important;
      }
    }
  }
  .ivu-select-item {
    white-space: nowrap !important;
  }
}
</style>